package com.sgb.kjwl.view.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;

import com.google.gson.Gson;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentNewWebViewX5Binding;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.H5MsgEntity;
import com.swgk.core.util.ACAdminDialogUtils;
import com.sgb.kjwl.utils.AndroidBug5497Workaround;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.utils.WebJsConstants;
import com.swgk.core.event.EventConstant;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.SharedPreferenceUtil;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.ycbjie.webviewlib.base.X5WebChromeClient;
import com.ycbjie.webviewlib.bridge.DefaultHandler;
import com.ycbjie.webviewlib.view.X5WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import static com.swgk.core.util.ACAdminDialogUtils.TYPE_NO_LOGIN;

/**
 * 作者:张磊
 * 日期:2021/1/26 0026
 * 说明:
 */
public class NewWebViewX5Fragment extends AppFragment {

    private static FragmentNewWebViewX5Binding binding;
    private static X5WebChromeClient chromeClient;
    private static String mToken;
    private static final int REQUEST_CODE_REFRESH = 3;
    private static String mUrl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_new_web_view_x5, container, false);
        UiUtil.setStatusBarLightMode(getActivity(), true);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initWebSetting();
    }

    private void initView() {
        mUrl = getActivity().getIntent().getStringExtra("url");
        binding.webView.loadUrl(mUrl);
        H5MsgEntity tokenEntity = new H5MsgEntity();
        tokenEntity.data = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourcePCToken, "");
        tokenEntity.msgType = "cmd_userToken";
        mToken = new Gson().toJson(tokenEntity);
        binding.ivBack.setOnClickListener(v -> goback());
        binding.tvTitle.setText(getActivity().getIntent().getStringExtra("title"));
        AndroidBug5497Workaround.assistActivity(getActivity());
    }

    public void goback() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack();
        } else {
            getActivity().finish();
        }
    }

    public static X5WebView getWebView() {
        return binding.webView;
    }

    private void initWebSetting() {
        initWebViewBridge();
        binding.progress.show();
        binding.progress.setColor(this.getResources().getColor(R.color.transparent));
        binding.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        binding.webView.getSettings().setDomStorageEnabled(true);
        binding.webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        binding.webView.getSettings().setAppCacheEnabled(true);
        binding.webView.getSettings().setJavaScriptEnabled(true);
        chromeClient = new X5WebChromeClient(binding.webView, getActivity()) {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
            }
        };
        binding.webView.setWebChromeClient(chromeClient);
        binding.webView.callHandler(WebJsConstants.CALLEDHANDLER, getActivity().getIntent().getStringExtra("data"), data -> {
        });
        binding.webView.callHandler(WebJsConstants.CALLEDHANDLER, mToken, data -> {
        });
    }

    // 注册JS方法 js调用java
    @JavascriptInterface
    public void initWebViewBridge() {
        binding.webView.setDefaultHandler(new DefaultHandler());
        binding.webView.registerHandler(WebJsConstants.SEND_TITLE, (data, function) -> {
            System.out.println("title==" + data);
            binding.tvTitle.setText(new Gson().fromJson(data, Bean.class).title);
        });

        binding.webView.registerHandler(WebJsConstants.CALLBACKHANDLER, (data, function) -> {
            System.out.println("js回调的数据==" + data);
            UiUtil.sendMsg(EventConstant.EVENT_REFRESH, null);
            H5MsgEntity json = new Gson().fromJson(data, H5MsgEntity.class);
            try {
                if (json.msgType.contains("cmd_loadingHud")) {
                    if (String.valueOf(json.data).contains("show")) {
                        DialogHelper.showProgressDialog(getActivity(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
                    } else {
                        DialogHelper.dismissProgressDialog();
                    }
                }
            } catch (Exception e) {

            }
            if (json.msgType.contains("cmd_userToken")) {
                function.onCallBack(mToken);
            } else if (json.msgType.contains("cmd_closePage")) {
                getActivity().finish();
            } else if (json.msgType.contains("cmd_pushToCheckstand")) {
                PersonPayActivity.start(getActivity(), new Gson().toJson(json.data), REQUEST_CODE_REFRESH,getActivity().getIntent().getBooleanExtra("isUser",false));
            } else if (json.msgType.contains("cmd_Tokenlose")) {
                //登录失效
                ACAdminDialogUtils.showACDialog(TYPE_NO_LOGIN, getContext());
            } else {
                if (!TextUtils.isEmpty(getActivity().getIntent().getStringExtra("data"))) {
                    function.onCallBack(getActivity().getIntent().getStringExtra("data"));
                }
            }
        });
    }

    public static void ActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE) {
            chromeClient.uploadMessage(intent, resultCode);
        } else if (requestCode == X5WebChromeClient.FILE_CHOOSER_RESULT_CODE_5) {
            chromeClient.uploadMessageForAndroid5(intent, resultCode);
        } else if (requestCode == REQUEST_CODE_REFRESH) {
            binding.webView.loadUrl(mUrl);
            binding.webView.callHandler(WebJsConstants.CALLEDHANDLER, mToken, data -> {
            });
        }
    }


}